package com.bsoft.gol.hcb.service.prescriptionCirculation;

import com.bsoft.gol.hcb.dao.prescriptionCirculation.*;
import com.bsoft.gol.hcb.utils.CommonUtils;
import com.bsoft.gol.hcb.utils.Constants;
import com.bsoft.gol.hcb.utils.DateUtils;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import ctd.controller.exception.ControllerException;
import ctd.dictionary.Dictionary;
import ctd.persistence.exception.DAOException;
import ctd.spring.boot.annotation.SsdevService;
import ctd.util.JSONUtils;
import ctd.util.annotation.RpcService;
import hcn.base.BasePropertyConfig;
import hcn.common.CodeDefinition;
import hcn.ods.PayTrade;
import hcn.pay.PayType;
import hcn.util.ConsultUtil;
import hcn.util.validation.AnnotaionException;
import hcn.util.validation.StringUtil;
import hcn.util.validation.ValidationUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import pcn.bean.consultation.*;
import pcn.bean.consultation.ExpressOrderStatusVo.Specific;
import pcn.bean.express.ExpreeInfoVo;
import pcn.consultation.ExpressOrder;
import pcn.consultation.ExpressOrderDetail;
import pcn.enums.*;
import pcn.prescribe.OdsExpressInfo;
import pcn.prescribe.OdsOrderToPrescription;
import pcn.prescribe.OdsPrescriptionOrder;
import pcn.prescriptionCirculation.OdsOrderPrescriptionDrug;
import pcn.prescriptionCirculation.OdsOrderPrescriptionInfo;
import pcn.service.consultation.ExpressOrderService;
import pcn.sign.ExpressCompany;
import service.rpc.BasePropertyConfigIntf;
import service.rpc.ExpressFeeIntf;
import service.rpc.PayTradeIntf;

import java.math.BigDecimal;
import java.util.*;
@SsdevService("expressOrderService")
public class ExpressOrderServiceImpl implements ExpressOrderService {
    private static final Logger LOGGER = LoggerFactory.getLogger(ExpressOrderServiceImpl.class);

    @Autowired
    private ExpreeOrderDetailDAO expreeOrderDetailDAO;
    @Autowired
    private ExpreeOrderDAO expreeOrderDAO;
    @Autowired
    private OdsPrescriptionOrderDAO odsPrescriptionOrderDAO;//订单表
    @Autowired
    private OdsOrderToPrescriptionDAO odsOrderToPrescriptionDAO;//订单明细
    @Autowired
    private OdsOrderPrescriptionInfoDAO odsOrderPrescriptionInfoDAO;//订单处方主表
    @Autowired
    private OdsOrderPrescriptionDrugDAO odsOrderPrescriptionDrugDAO;//订单处方明细表
    @Autowired
    private OdsExpressInfoDAO odsExpressInfoDAO;//订单物流信息表
    @Autowired
    @Qualifier("hcnPayTradeService")
    private PayTradeIntf payTradeService;
    @Autowired
    private ExpressFeeIntf expressFeeService;
    @Autowired
    private BasePropertyConfigIntf basePropertyConfigIntf;

    @Autowired
    private DrugOrdersService drugOrderService;
    @Value("${express_query_url}")
    private String expressQueryUrl;

    /**
     * 保存快递单详情
     *
     * @param orderList
     */
    @Override
    public void saveExpressOrderDetail(List<OrderDetailVo> orderList) {
        List<ExpressOrderDetail> orderDetails = new ArrayList<>();
        ExpressOrderDetail expressOrderDetail = new ExpressOrderDetail();
        for (OrderDetailVo orderDetailVo : orderList) {
            BeanUtils.copyProperties(orderDetailVo, expressOrderDetail);
            expreeOrderDetailDAO.save(expressOrderDetail);
        }
        ExpressOrder expressOrder = expreeOrderDAO.get(orderList.get(0).getExpressOrderId());
        if (CommonUtils.isEmpty(expressOrder)) {
            return;
        }
        //修改订单状态为已发货
//        expressOrder.setStatus((byte)2);
        expreeOrderDAO.update(expressOrder);
    }

    /**
     * @param request
     * @return List<ExpressOrderVo>
     * @author zhusm@bsoft.com
     * @description 药品配送列表
     * @date 2019/12/26
     */
    @Override
    public Map findExpreeOrder(ExpressOrderQo request) {
        Map<String, Object> returnMap = new HashMap<>();

        //转化查询入参
        if (Constants.CONSULT_TYPE_RETURNVISIT.equals(request.getBusinessType())) {
            request.setBusinessType(OrderTypeEnum.FZPYCF.getTitle());
        }

        //获取药品订单主表信息，left join 订单发货明细表,查询sql大部分表都是一对一的，distinct 去重
        List<ExpressOrderVo> expressOrderVos = odsPrescriptionOrderDAO.findOdsPrescriptionOrders(request);
        Long count = odsPrescriptionOrderDAO.getOdsPrescriptionOrdersCount(request);

        returnMap.put("total", count);
        returnMap.put("pageNo", request.getPageNo());

        //若是订单为空，直接返回
        if (CommonUtils.isEmpty(expressOrderVos)) {
            return returnMap;
        }

        //分页的订单号集合
        List<String> orderIds = new ArrayList<>();

        for (ExpressOrderVo expressOrderVo : expressOrderVos) {
            //合并订单号
            orderIds.add(expressOrderVo.getOrderId());
        }

        //订单的快递公司代码map，一对多
        Map<String, Set<String>> expressCodeMap = new HashMap<>();
        //订单的物流id
        Map<String, Set<String>> expressOrderIdMap = new HashMap<>();
        //订单的问诊类型
        Map<String, Set<String>> consultTypeMap = new HashMap<>();
        //物流快递类型
        Map<String, String> expressNameMap = new HashMap<>();

        if (CommonUtils.isNotEmpty(orderIds)) {
            Dictionary dictionary = ConsultUtil.getDictionary(DictionaryEnum.CONSULT_TYPE.getDicCode());
            //查询药品订单所对应的问诊类型，物流公司，物流单号
            List<Map> prescriptions = odsOrderToPrescriptionDAO.findOrderIds(orderIds);

            if (CommonUtils.isNotEmpty(prescriptions)) {

                for (Map prescription : prescriptions) {
                    String orderId = (String) prescription.get("orderId");
                    String businessType = (String) prescription.get("businessType");
                    String expressCode = (String) prescription.get("expressCode");
                    String expressOrderId = (String) prescription.get("expressOrderId");
                    String expressName = (String) prescription.get("expressName");

                    //合并重复的订单号的快递公司代码
                    Set<String> expressCodeSet = expressCodeMap.get(orderId);
                    if (null == expressCodeSet) {
                        expressCodeSet = new HashSet<>();
                    }
                    if (CommonUtils.isNotEmpty(expressCode)) {
                        expressCodeSet.add(expressCode);
                        expressCodeMap.put(orderId, expressCodeSet);
                        expressNameMap.put(expressCode, expressName);
                    }

                    //合并重复的订单号的快递公司物流单号
                    Set<String> expressOrderIdSet = expressOrderIdMap.get(orderId);
                    if (null == expressOrderIdSet) {
                        expressOrderIdSet = new HashSet<>();
                    }
                    if (CommonUtils.isNotEmpty(expressOrderId)) {
                        expressOrderIdSet.add(expressOrderId);
                        expressOrderIdMap.put(orderId, expressOrderIdSet);
                    }

                    //合并重复的订单号的问诊类型
                    Set<String> consultTypeSet = consultTypeMap.get(orderId);
                    if (null == consultTypeSet) {
                        consultTypeSet = new HashSet<>();
                    }
                    if (CommonUtils.isNotEmpty(businessType)) {
                        boolean returnVisitFlag = ConsultUtil.checkConsultType(Arrays.asList(ConsultModeEnum.REVISIT.getMode()), null, businessType);
                        if (returnVisitFlag) {
                            consultTypeSet.add(dictionary.getText(businessType));
                        } else {
                            consultTypeSet.add(businessType);
                        }
                        consultTypeMap.put(orderId, consultTypeSet);
                    }
                }

            }

            for (ExpressOrderVo expressOrderVo : expressOrderVos) {
                //相同订单id，不同的问诊类型合并放到一个字符串里面，用逗号分割
                Set<String> consultTypeSet = consultTypeMap.get(expressOrderVo.getOrderId());
                if (CommonUtils.isNotEmpty(consultTypeSet)) {
                    StringBuffer businessTypeBuffer = new StringBuffer();
                    StringBuffer businessTypeNameBuffer = new StringBuffer();
                    for (String consultType : consultTypeSet) {
                        businessTypeBuffer.append(",").append(consultType);
                        businessTypeNameBuffer.append(",").append(dictionary.getText(consultType));
                    }
                    expressOrderVo.setBusinessType(businessTypeBuffer.substring(1));
                    expressOrderVo.setBusinessTypeName(businessTypeNameBuffer.substring(1));
                }

                //相同订单id，不同的物流公司代码合并放到一个字符串里面，用逗号分割
                Set<String> expressCodeSet = expressCodeMap.get(expressOrderVo.getOrderId());
                if (CommonUtils.isNotEmpty(expressCodeSet)) {
                    StringBuffer expressCodeBuffer = new StringBuffer();
                    for (String expressCode : expressCodeSet) {
                        String expressName = expressNameMap.get(expressCode);
                        expressCodeBuffer.append(",").append(expressName);
                    }
                    expressOrderVo.setExpressCode(expressCodeBuffer.substring(1));
                }

                //相同订单id，不同的物流公司代码合并放到一个字符串里面，用逗号分割
                Set<String> expressOrderIdSet = expressOrderIdMap.get(expressOrderVo.getOrderId());
                if (CommonUtils.isNotEmpty(expressOrderIdSet)) {
                    StringBuffer expressOrderIdBuffer = new StringBuffer();
                    for (String expressOrderId : expressOrderIdSet) {
                        expressOrderIdBuffer.append(",").append(expressOrderId);
                    }
                    expressOrderVo.setExpressOrderId(expressOrderIdBuffer.substring(1));
                }
            }
        }

        returnMap.put("list", expressOrderVos);
        return returnMap;
    }


    /**
     * 删除发货详情
     *
     * @param detailId
     * @throws ControllerException
     */
    @RpcService
    @Override
    public void deleteExpreeOrderDetail(String detailId) throws ControllerException {
        if (CommonUtils.isEmpty(detailId)) {
            return;
        }
        expreeOrderDetailDAO.remove(detailId);
    }


    /**
     * @param orderId 订单主表id
     * @return
     */
    @Override
    public ExpreeOrderDetailResponseBean findExpreeOrderDetail(String orderId) throws ControllerException {
        try {
            if (StringUtil.isEmpty(orderId)) {
                throw new ControllerException(CodeDefinition.EXPRESSORDER_PARAMS_FAILED, "orderId can not be null");
            }
            //订单信息
            OdsPrescriptionOrder odsPrescriptionOrder = null;
            //供货商发货表，一个订单只对应一条记录
            List<ExpressOrder> expressOrders = null;
            //订单处方主表信息
            List<OdsOrderPrescriptionInfo> odsOrderPrescriptionInfoList = null;
            //处方药品信息集合
            List<ExpreeOrderDetailResponseBean.Prescription> prescriptions = null;
            //支付订单信息
            PayTrade payTrade = null;
            //发货快递明细集合
            List<ExpressOrderDetail> expressOrderDetails = null;
            //订单物流信息
            OdsExpressInfo odsExpressInfo = null;
            //处方编号字符串
            StringBuilder builder = new StringBuilder();
            //问诊类型中文
            StringBuffer consultTypeNameBuffer = new StringBuffer();
            try {
                //订单明细集合
                List<OdsOrderToPrescription> odsOrderToPrescriptions = odsOrderToPrescriptionDAO.findOrderId(orderId);
                //订单里面的问诊记录id集合
                List<String> consultIds = new ArrayList<>(odsOrderToPrescriptions.size());
                //订单的处方id集合
                List<String> prescriptionInfoIds = new ArrayList<>();

                Dictionary dictionary = ConsultUtil.getDictionary(DictionaryEnum.CONSULT_TYPE.getDicCode());

                //遍历订单明细，获取处方标识集合
                for (OdsOrderToPrescription odsOrderToPrescription : odsOrderToPrescriptions) {
                    //根据订单明细文档类型来获取处方号id集合
                    if (FeeTypeEnum.XIYAO.getTitle().equals(odsOrderToPrescription.getFeeType()) || FeeTypeEnum.CHENGYAO.getTitle().equals(odsOrderToPrescription.getFeeType()) || FeeTypeEnum.CAOYAO.getTitle().equals(odsOrderToPrescription.getFeeType())) {
                        prescriptionInfoIds.add(odsOrderToPrescription.getFeeCode());//处方id
                    }

                    if (CommonUtils.isNotEmpty(odsOrderToPrescription.getConsultType())) {
                        String consultTypeName = dictionary.getText(odsOrderToPrescription.getConsultType());
                        if (CommonUtils.isNotEmpty(consultTypeName)) {
                            consultTypeNameBuffer.append(",").append(consultTypeName);
                        }
                    }
                }


                //处方主表信息需要从订单明细表获取
                if (CommonUtils.isNotEmpty(prescriptionInfoIds)) {
                    odsOrderPrescriptionInfoList = odsOrderPrescriptionInfoDAO.findByOrderId(orderId);
                    for (OdsOrderPrescriptionInfo odsOrderPrescriptionInfo : odsOrderPrescriptionInfoList) {
                        if (CommonUtils.isNotEmpty(odsOrderPrescriptionInfo.getPrescriptionNumber())) {
                            builder.append("/" + odsOrderPrescriptionInfo.getPrescriptionNumber());
                        }
                    }

                    prescriptions = odsOrderPrescriptionDrugDAO.findOdsPrescriptionInfos(orderId);
                }

                //获取订单信息
                odsPrescriptionOrder = odsPrescriptionOrderDAO.get(orderId);
                if (null != odsPrescriptionOrder) {
                    //获取支付订单信息
                    payTrade = payTradeService.getPayTrade(odsPrescriptionOrder.getTradeNo());
                }
                //获取发货订单表信息
                expressOrders = expreeOrderDAO.findByOrderId(orderId);
                //获取订单物流信息
                odsExpressInfo = odsExpressInfoDAO.getOdsExpressInfo(orderId);
                //快递物流明细集合
                List<String> expressIds = new ArrayList<>();
                for (ExpressOrder expressOrder : expressOrders) {
                    expressIds.add(expressOrder.getExpressId());
                }
                if (CommonUtils.isNotEmpty(expressIds)) {
                    expressOrderDetails = expreeOrderDetailDAO.findByExpressId(expressIds);
                }
            } catch (DAOException e) {
                e.printStackTrace();
                throw new ControllerException(CodeDefinition.EXPRESSORDER_SYSTEM_FAILED, "系统内部错误");
            }
            ExpreeOrderDetailResponseBean expreeOrderDetailResponseBean = new ExpreeOrderDetailResponseBean();
            expreeOrderDetailResponseBean.setOrderNo(orderId);
            expreeOrderDetailResponseBean.setOrderStatus(odsPrescriptionOrder.getOrderStatus());
            expreeOrderDetailResponseBean.setPayStatus(odsPrescriptionOrder.getPayStatus());//支付状态
            expreeOrderDetailResponseBean.setPayWay(odsPrescriptionOrder.getPayWay());//支付方式  1在线支付
            expreeOrderDetailResponseBean.setOrderDate(DateUtils.toallTime(odsPrescriptionOrder.getCreateTime()));
            if(StringUtils.isNotEmpty(consultTypeNameBuffer)){
                expreeOrderDetailResponseBean.setOrderSource(consultTypeNameBuffer.substring(1));
            }
            expreeOrderDetailResponseBean.setInvoiceNo(odsPrescriptionOrder.getInvoiceNumber());
            expreeOrderDetailResponseBean.setPrescriptionNumber(builder.length() > 0 ? builder.toString().substring(1) : builder.toString());
            expreeOrderDetailResponseBean.setOrderTotalPrice(odsPrescriptionOrder.getTotalFee());
            //订单药品明细
            expreeOrderDetailResponseBean.setOutpatientDepartmentNo(odsPrescriptionOrder.getPatientMedicalCardNumber());
            expreeOrderDetailResponseBean.setPatientName(odsPrescriptionOrder.getPersonName());
            expreeOrderDetailResponseBean.setPrescriptionDate(CommonUtils.isEmpty(odsOrderPrescriptionInfoList) ? null : odsOrderPrescriptionInfoList.get(0).getCreateTime());
            //处方明细
            //处方总金额
            BigDecimal totalPrice = new BigDecimal(0);
            if (CommonUtils.isNotEmpty(prescriptions)) {
                for (ExpreeOrderDetailResponseBean.Prescription prescription : prescriptions) {

                    //西药 中成药
                    if (PrescriptionTypeEnum.WESRERN_MEDICINE.getTitle().equals(prescription.getDrugType()) || PrescriptionTypeEnum.CHINESE_PATENT_MEDICINE.getTitle().equals(prescription.getDrugType())) {
                        double price = prescription.getUnitPrice() == null ? 0 : prescription.getUnitPrice();
                        BigDecimal medicineTotalFee = new BigDecimal(price).multiply(new BigDecimal(prescription.getNumber() == null ? 0 : prescription.getNumber())).setScale(2, BigDecimal.ROUND_HALF_UP);
                        prescription.setTotalPrice(medicineTotalFee.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
                        totalPrice = totalPrice.add(medicineTotalFee);

                        //草药
                    } else if (PrescriptionTypeEnum.CHINESE_MEDICINE.getTitle().equals(prescription.getDrugType())) {
                        double price = prescription.getUnitPrice() == null ? 0 : prescription.getUnitPrice();
                        BigDecimal medicineTotalFee = new BigDecimal(price).multiply(new BigDecimal(prescription.getNumber() == null ? 0 : prescription.getNumber())).setScale(2, BigDecimal.ROUND_HALF_UP);
                        prescription.setTotalPrice(medicineTotalFee.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
                        //订单总金额
                        totalPrice = totalPrice.add(medicineTotalFee.multiply(new BigDecimal(prescription.getNumberOfPackets() == null ? 0 : prescription.getNumberOfPackets())));
                    }

                }
                expreeOrderDetailResponseBean.setPrescriptionDetailed(prescriptions);
            }
            expreeOrderDetailResponseBean.setTotalPrice(totalPrice.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());

            //包裹信息
            List<ExpreeOrderDetailResponseBean.PackageInfo> packageInfos = new ArrayList<>();
            double express_fee = 0.00;
            List<String> expressIds = new ArrayList<>();
            if (CommonUtils.isNotEmpty(expressOrderDetails)) {
                for (int i = 1; i <= expressOrderDetails.size(); i++) {
                    for (ExpressOrder expressOrder : expressOrders) {
                        if (expressOrderDetails.get(i - 1).getExpressId().equals(expressOrder.getExpressId())) {
                            ExpreeOrderDetailResponseBean.PackageInfo packageInfo = new ExpreeOrderDetailResponseBean.PackageInfo();
                            packageInfo.setPackageNum(i);
                            packageInfo.setDetailId(expressOrderDetails.get(i - 1).getDetailId());
                            packageInfo.setExpressId(expressOrderDetails.get(i - 1).getExpressId());
                            packageInfo.setExpressNo(expressOrderDetails.get(i - 1).getExpressOrderId());
                            packageInfo.setExpressCode(expressOrderDetails.get(i - 1).getExpressCode());
                            packageInfo.setDeliveryTime(expressOrder.getDeliverTime() == null ? null : DateUtils.toDateForYYYYMMddHHmmss(expressOrder.getDeliverTime()));
                            packageInfo.setSignForTime(expressOrder.getConfirmReceiptTime());
                            packageInfo.setSignForStatus(expressOrder.getConfirmReceipt());
                            packageInfo.setExpressContent(expressOrderDetails.get(i - 1).getExpressContent());
                            packageInfo.setExpressFee(expressOrderDetails.get(i - 1).getExpressFee());
                            packageInfo.setDeliverFlag(expressOrder.getDeliverFlag());
                            packageInfos.add(packageInfo);
                            express_fee += expressOrderDetails.get(i - 1).getExpressFee() == null ? 0.00 : expressOrderDetails.get(i - 1).getExpressFee();
                            expressIds.add(expressOrderDetails.get(i - 1).getExpressId());
                        }
                    }
                }
            }
            int index = expressIds.size();
            for (ExpressOrder expressOrder : expressOrders) {
                if (!expressIds.contains(expressOrder.getExpressId())) {
                    index += 1;
                    ExpreeOrderDetailResponseBean.PackageInfo packageInfo = new ExpreeOrderDetailResponseBean.PackageInfo();
                    packageInfo.setPackageNum(index);
                    packageInfo.setExpressId(expressOrder.getExpressId());
                    packageInfo.setExpressNo(null);
                    packageInfo.setExpressCode(expressOrder.getExpressCode());
                    packageInfo.setDeliveryTime(expressOrder.getDeliverTime() == null ? null : DateUtils.toDateForYYYYMMddHHmmss(expressOrder.getDeliverTime()));
                    packageInfo.setSignForTime(null);
                    packageInfo.setSignForStatus(expressOrder.getConfirmReceipt());
                    packageInfo.setExpressContent("");
                    packageInfo.setExpressFee(null);
                    packageInfo.setDeliverFlag(expressOrder.getDeliverFlag());
                    packageInfos.add(packageInfo);
                }
            }

            //配送信息
            if (null != odsExpressInfo) {
                expreeOrderDetailResponseBean.setDistributionMode(odsExpressInfo.getTakeWay());
                expreeOrderDetailResponseBean.setDistributionFee(express_fee);
                expreeOrderDetailResponseBean.setAddressee(odsExpressInfo.getReciverName());
                expreeOrderDetailResponseBean.setContactNumber(odsExpressInfo.getTelephone());
                expreeOrderDetailResponseBean.setDetailedAddress(odsExpressInfo.getAddress());
            }
            expreeOrderDetailResponseBean.setPackageInfos(packageInfos);
            //支付信息
            expreeOrderDetailResponseBean.setPayTime(payTrade == null ? null : payTrade.getTradeTime());
            expreeOrderDetailResponseBean.setPayMode(payTrade == null ? "" : PayType.getDisplay(payTrade.getPayType()));
            expreeOrderDetailResponseBean.setPayPrice(payTrade == null ? 0.00 : payTrade.getTotalFee());
            expreeOrderDetailResponseBean.setPayAccount(payTrade == null ? "" : payTrade.getAccount());
            return expreeOrderDetailResponseBean;
        } catch (ControllerException e) {
            throw new ControllerException(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            throw new ControllerException("获取详情失败");
        }
    }

    /**
     * @description: 获取快递物流信息
     * @author: chenJij@bsoft.com.cn
     * @date: 2020/1/4 14:23
     */
    @Override
    @RpcService
    public List<Map<String, Object>> queryDrugOrderExpressInfoList(QueryDrugOrderExpressInfoListQo qo) throws ControllerException {
        if (CommonUtils.isEmpty(qo.getOrderId())) {
            throw new ControllerException("订单id不能为空");
        }
        List<Map<String, Object>> expressList = Lists.newArrayList();
        List<ExpreeInfoVo> expressInfoVoList = drugOrderService.queryExpressInfo(qo.getOrderId());
        if (CommonUtils.isEmpty(expressInfoVoList)) {
            return expressList;
        }
        for (ExpreeInfoVo expreeInfoVo : expressInfoVoList) {
            Map<String, Object> map = Maps.newHashMap();
            map.put("expressUrl", expressQueryUrl + "?com=" + expreeInfoVo.getExpreeCompanyCode() + "&nu=" + expreeInfoVo.getExpreeNumber());
            map.put("logisticNo", expreeInfoVo.getExpreeNumber());
            expressList.add(map);
        }
        return expressList;
    }

    /**
     * 下单查看物流(需要对接api)
     *
     * @param orderId
     * @return
     */
    @Override
    @RpcService
    public List<ExpressOrderDetailVo> getExpressOrderDetail(String orderId) {
        List<ExpressOrderDetailVo> expressOrderDetailVos = expreeOrderDAO.getExpressOrder(orderId);

        if (CommonUtils.isEmpty(expressOrderDetailVos)) {
            return null;
        }
        for (ExpressOrderDetailVo expressOrderDetailVo : expressOrderDetailVos) {
            //调用api查询物流配送情况
            expressOrderDetailVo.setExportStatus("");
            expressOrderDetailVo.setExpressMessage(new ArrayList<String>());
            expressOrderDetailVo.setExpressPhone("");
        }
        return expressOrderDetailVos;
    }

    /*
     * @author zhusm@bsoft.com
     * @description 获取药品配送 来源，状态，公司
     * @date 2019/12/31
     * @param []
     * @return java.util.List
     */
    @Override
    @RpcService
    public ExpressOrderStatusVo getExpressOrderStatus() throws ControllerException {
        ExpressOrderStatusVo expressOrderStatusVo = new ExpressOrderStatusVo();
        List<ExpressCompany> expressallCode = expressFeeService.findAllCode();
        if (CommonUtils.isNotEmpty(expressallCode)) {
            List<Specific> express = new ArrayList<>();
            for (ExpressCompany expressCompany : expressallCode) {
                Specific specific = new Specific();
                specific.setKey(expressCompany.getExpressCode());
                specific.setValue(expressCompany.getExpressName());
                express.add(specific);
            }
            expressOrderStatusVo.setExpress(express);
        }
        return expressOrderStatusVo;
    }

    /**
     * @param requests
     * @return void
     * @author zhusm@bsoft.com
     * @description 录入快递信息
     * @date 2019/12/31
     */
    @Override
    @RpcService
    public void enterExpress(List<EnterExpressQo> requests) throws ControllerException {
        LOGGER.info("录入快递信息：" + JSONUtils.toString(requests));
        if (CommonUtils.isEmpty(requests)) {
            throw new ControllerException(CodeDefinition.EXPRESSORDER_PARAMS_FAILED, "入参不能为空！");
        }
        for (EnterExpressQo request : requests) {
            try {

                ValidationUtil.validation(request);//入参格式校验

            } catch (AnnotaionException e) {
                e.printStackTrace();
            }

            OdsPrescriptionOrder odsPrescriptionOrder = odsPrescriptionOrderDAO.get(request.getOrderId());
            if (null == odsPrescriptionOrder) {
                throw new ControllerException(CodeDefinition.EXPRESSORDER_SERVICE_FAILED, "订单不存在！");
            }
            if (!"1".equals(odsPrescriptionOrder.getPayStatus())) {
                throw new ControllerException(CodeDefinition.EXPRESSORDER_SERVICE_FAILED, "订单尚未支付！");
            }
            //修改发货快递信息
            if (request.getUpdate()) {
                try {
                    //获取所有的快递明细
                    ExpressOrderDetail expressOrderDetail = expreeOrderDetailDAO.getDetailBydetailId(request.getDetailId());
                    if (CommonUtils.isNotEmpty(expressOrderDetail)) {
                        expressOrderDetail.setExpressCode(StringUtil.isEmpty(request.getExpressCode()) ? expressOrderDetail.getExpressCode() : request.getExpressCode());
                        expressOrderDetail.setExpressContent(StringUtil.isEmpty(request.getExpressContent()) ? expressOrderDetail.getExpressContent() : request.getExpressContent());
                        expressOrderDetail.setExpressOrderId(StringUtil.isEmpty(request.getExpressNo()) ? expressOrderDetail.getExpressOrderId() : request.getExpressNo());
                        //修改快递明细
                        ExpressCompany expressCompany = expressFeeService.getExpressCompanyByCode(request.getExpressCode());
                        if (CommonUtils.isNotEmpty(expressCompany)){
                            expressOrderDetail.setExpressName(expressCompany.getExpressName());
                        }
                        expreeOrderDetailDAO.update(expressOrderDetail);
                    }
                } catch (DAOException e) {
                    e.printStackTrace();
                    throw new ControllerException(CodeDefinition.EXPRESSORDER_SYSTEM_FAILED, "系统内部错误");
                }
                //新增发货快递信息
            } else {
                //订单状态改为待收货
                odsPrescriptionOrder.setOrderStatus("2");
                odsPrescriptionOrderDAO.update(odsPrescriptionOrder);
                //获取发货订单表
                ExpressOrder expressOrder = expreeOrderDAO.getByOrderId(request.getOrderId());
                //修改发货状态   1 已发货
                expressOrder.setDeliverFlag("1");
                //修改确认收货状态   0 未收货
                expressOrder.setConfirmReceipt("0");
                //修改删除状态  0 未删除
                expressOrder.setDeleteFlag("0");
                //添加发货时间
                expressOrder.setDeliverTime(DateUtils.toallTime(new Date()));
                //修改
                expressOrder.setExpressCode(request.getExpressCode());
                //医生接诊时间获取
                BasePropertyConfig receiptPropertyConfig = null;


                //自动确认收货倒计时（天）
                int days = 7;
                List<OdsOrderToPrescription> odsOrderToPrescriptions = odsOrderToPrescriptionDAO.findOrderId(odsPrescriptionOrder.getOrderId());
                if (CommonUtils.isNotEmpty(odsOrderToPrescriptions)) {
                    for (OdsOrderToPrescription odsOrderToPrescription : odsOrderToPrescriptions) {
                        try {
                            if (OrderTypeEnum.FZPYCF.getTitle().equals(odsOrderToPrescription.getConsultType()) || OrderTypeEnum.YZSCF.getTitle().equals(odsOrderToPrescription.getConsultType())) {
                                //复诊配药自动确认收货时限(单位:天)
                                receiptPropertyConfig = basePropertyConfigIntf.getPropertyConfigByPropertyCode("012205", odsPrescriptionOrder.getOrgId());

                                if (null != receiptPropertyConfig) {
                                    days = Integer.valueOf(receiptPropertyConfig.getPropertyData());
                                }

                                break;
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }

                Calendar calendar = Calendar.getInstance();
                calendar.setTime(new Date());
                calendar.add(Calendar.DAY_OF_MONTH, days);

                expressOrder.setReceiptExpireTime(calendar.getTime());
                ExpressOrder order = expreeOrderDAO.update(expressOrder);

                OdsExpressInfo odsExpressInfo = odsExpressInfoDAO.getOdsExpressInfo(request.getOrderId());
                if (odsExpressInfo != null) {
                    odsExpressInfo.setDeliveryTime(new Date());
                    odsExpressInfoDAO.update(odsExpressInfo);
                }

                try {
//                    for (int i = 0; i < requests.size(); i++) {
                    //新增快递明细
                    ExpressCompany expressCompany = expressFeeService.getExpressCompanyByCode(request.getExpressCode());

                    ExpressOrderDetail detail = new ExpressOrderDetail();
                    detail.setCompanyId(order.getCompanyId());
                    detail.setDetailId(UUID.randomUUID().toString());
                    detail.setExpressId(order.getExpressId());
                    detail.setExpressCode(request.getExpressCode());
                    if (expressCompany != null) {
                        detail.setExpressName(expressCompany.getExpressName());
                    }
                    detail.setExpressOrderId(request.getExpressNo());
                    detail.setExpressFee(null);
                    detail.setExpressContent(request.getExpressContent());
                    expreeOrderDetailDAO.save(detail);
//                    }
                } catch (DAOException e) {
                    //出现异常 统一删除物流数据  前端重新保存
                    List<ExpressOrderDetail> list = expreeOrderDetailDAO.findByExId(order.getExpressId());
                    for (ExpressOrderDetail expressOrderDetail : list) {
                        expreeOrderDetailDAO.remove(expressOrderDetail.getDetailId());
                    }
                    e.printStackTrace();
                    throw new ControllerException(CodeDefinition.EXPRESSORDER_SYSTEM_FAILED, "系统内部错误");
                }
            }
        }
    }

    /**
     * @param map
     * @return void
     * @author zhusm@bsoft.com
     * @description 录入快递费用
     * @date 2019/12/31
     */
    @Override
    @RpcService
    public void enterExpresFee(Map<String, Object> map) throws ControllerException {
        try {
            String orderId = (String) map.get("orderId");
            String expressfee = (String) (map.get("expressFee") + "");
            String detailId = (String) map.get("detailId");
            if (CommonUtils.isEmpty(expressfee)) {
                throw new ControllerException(CodeDefinition.EXPRESSORDER_SERVICE_FAILED, "快递费用不能为空！");
            }
            Double fee = 0d;
            try {
                fee = Double.valueOf(expressfee);
            } catch (Exception e) {
                throw new ControllerException(CodeDefinition.EXPRESSORDER_SERVICE_FAILED, "快递费用必须为数字！");
            }
            if (fee <= 0.00) {
                throw new ControllerException(CodeDefinition.EXPRESSORDER_SERVICE_FAILED, "快递费用不能为0！");
            }
            OdsPrescriptionOrder odsPrescriptionOrder = odsPrescriptionOrderDAO.get(orderId);

            if (null == odsPrescriptionOrder) {
                throw new ControllerException(CodeDefinition.EXPRESSORDER_SERVICE_FAILED, "此订单不存在！");
            }

            if (!"1".equals(odsPrescriptionOrder.getPayWay())) {
                throw new ControllerException(CodeDefinition.EXPRESSORDER_SERVICE_FAILED, "此订单为在线支付，不支持修改快递费！");
            }

            if (CommonUtils.isEmpty(detailId)) {
                throw new ControllerException(CodeDefinition.EXPRESSORDER_SERVICE_FAILED, "快递记录id不能为空！");
            }

            ExpressOrderDetail detail = expreeOrderDetailDAO.get(detailId);

            if (null == detail) {
                throw new ControllerException(CodeDefinition.EXPRESSORDER_SERVICE_FAILED, "此快递不存在！");
            }

            detail.setExpressFee(fee);

            expreeOrderDetailDAO.update(detail);

        } catch (ControllerException e) {
            throw new ControllerException(e.getMessage());
        } catch (DAOException e) {
            e.printStackTrace();
            throw new ControllerException(CodeDefinition.EXPRESSORDER_SYSTEM_FAILED, "修改快递费用失败");
        }
    }

    /**
     * @description: 获取药品名称列表
     * @author: chenJij@bsoft.com.cn
     * @date: 2021/9/7 11:30
     * @param: orderId
     * @return: java.util.List<java.lang.String>
     */
    @Override
    @RpcService
    public List<String> getDrugName(String orderId) throws ControllerException {
        if (StringUtil.isEmpty(orderId)) {
            throw new ControllerException(CodeDefinition.EXPRESSORDER_PARAMS_FAILED, "orderId can not be null！");
        }
        List<OdsOrderToPrescription> orderDetails = odsOrderToPrescriptionDAO.findOrderId(orderId);
        if (CommonUtils.isEmpty(orderDetails)) {
            throw new ControllerException(CodeDefinition.EXPRESSORDER_SERVICE_FAILED, "此订单不存在！");
        }
        List<String> drugNames = new ArrayList<>();
        List<OdsOrderPrescriptionDrug> odsPrescriptionDrugs = odsOrderPrescriptionDrugDAO.findByOrderId(orderId);
        if (CommonUtils.isNotEmpty(odsPrescriptionDrugs)) {
            for (OdsOrderPrescriptionDrug drug : odsPrescriptionDrugs) {
                drugNames.add(drug.getDrugName());
            }
            return drugNames;
        }

        return drugNames;
    }

    /**
     * @param request
     * @return void
     * @author zhusm@bsoft.com
     * @description 药品发货
     * @date 2020/1/8
     */
    @RpcService
    @Override
    public void durgDeliverGoods(Map request) throws ControllerException {
        String expressId = (String) request.get("expressId");
        String orderId = (String) request.get("orderId");
        if (StringUtil.isEmpty(expressId)) {
            throw new ControllerException(CodeDefinition.EXPRESSORDER_PARAMS_FAILED, "expressId can not be null！");
        }
        if (StringUtil.isEmpty(orderId)) {
            throw new ControllerException(CodeDefinition.EXPRESSORDER_PARAMS_FAILED, "orderId can not be null！");
        }
        List<OdsOrderToPrescription> orderDetails = odsOrderToPrescriptionDAO.findOrderId(orderId);
        if (CommonUtils.isEmpty(orderDetails)) {
            throw new ControllerException(CodeDefinition.EXPRESSORDER_SERVICE_FAILED, "此订单不存在！");
        }
        OdsPrescriptionOrder odsPrescriptionOrder = odsPrescriptionOrderDAO.get(orderId);
        if (!"1".equals(odsPrescriptionOrder.getPayStatus())) {
            throw new ControllerException(CodeDefinition.EXPRESSORDER_SERVICE_FAILED, "订单尚未支付！");
        }
        ExpressOrder expressOrder = expreeOrderDAO.get(expressId);
        expressOrder.setDeleteFlag("1");
        expressOrder.setDeliverTime(DateUtils.toallTime(new Date()));
        try {
            expreeOrderDAO.update(expressOrder);
        } catch (DAOException e) {
            e.printStackTrace();
            throw new ControllerException(CodeDefinition.EXPRESSORDER_SYSTEM_FAILED, "系统内部错误");
        }
    }
}
